﻿using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using Telerik.Web.UI;
using Aspose.Excel;

namespace LenderClearingHouse
{
  public partial class LvreoMasterList : InvestorAdminPage
  {
    protected void Page_Load(object sender, EventArgs e)
    {
      listFilter.SearchButton.Click += new ImageClickEventHandler(SearchButton_Click);
      RadAjaxManager.AjaxSettings.AddAjaxSetting(Grid, Grid);
    }

    protected override void OnInit(EventArgs e)
    {
      base.OnInit(e);

      GetSqlDataSource().Inserted += new SqlDataSourceStatusEventHandler(LvreoMasterList_Inserted);
    }

    protected override void CreateColumns(GridColumnCollection columns)
    {
        base.CreateColumns(columns);

        int index = Utilities.GetColumnIndex(columns, "ListingStatus");
        Utilities.MoveColumn(columns, "InvestorName", ref index);

        var col = new GridBoundColumn();
        columns.Insert(index, Utilities.CreateTemlateDateColumn("DateAccept", "Date Accept", 0));
        
        ++index;

        Utilities.RemoveColumn(columns, "CloseDate");
        columns.Insert(index, Utilities.CreateTemlateDateColumn("RECORDED_F", "Recorded - F", 2));

        index = Utilities.GetColumnIndex(columns, "ZipCode") + 1;
        Utilities.RemoveColumn(columns, "DateRecorded");
        columns.Insert(index, Utilities.CreateTemlateDateColumn("RECORDED_B", "Recorded - B", 2));
        
        index = Utilities.GetColumnIndex(columns, "Phase");
        Utilities.MoveColumn(columns, "AssessorDesc", ref index);
        columns[index - 1].HeaderStyle.Width = Unit.Pixel(INT_COMMON_WIDTH * 6);
        columns[index - 1].FilterControlWidth = Unit.Pixel(INT_COMMON_WIDTH * 6 - 40);

        Utilities.GetColumn(columns, "RehabCosts").HeaderText = "Estimated rehab costs";
               

        Utilities.RemoveColumn(columns, "Source");
        Utilities.RemoveColumn(columns, "EscrowCompany");

        GridTemplateColumn gtc = Utilities.CreateDollarColumn(columns, "NetSheet_SellingPrice", "Sale Price", false, 3, "#0.00");
        columns.Add(gtc);

        gtc = Utilities.CreateDollarColumn(columns, "EstimatedResale", "Estimated resale", false, 3, "#0.00");
        columns.Add(gtc);
    }

    protected override void Grid_ItemDataBound(object sender, GridItemEventArgs e)
    {
        base.Grid_ItemDataBound(sender, e);
        if (e.Item.IsInEditMode && e.Item is GridEditableItem)
        {
            GridEditableItem item = e.Item as GridEditableItem;

            TextBox txt = (TextBox)item["RECORDED_F"].Controls[0];
            txt.ReadOnly = true;
            if (!string.IsNullOrEmpty(txt.Text))
                txt.Text = Convert.ToDateTime(txt.Text).ToString("d");

            txt = (TextBox)item["RECORDED_B"].Controls[0];
            txt.ReadOnly = true;
            if (!string.IsNullOrEmpty(txt.Text))
                txt.Text = Convert.ToDateTime(txt.Text).ToString("d");
        }
        else
        {
            if (!(e.Item is GridDataItem)) return;

            GridDataItem itm = e.Item as GridDataItem;
            DataRowView drw = itm.DataItem as DataRowView;

            if (drw["RECORDED_B"] != DBNull.Value
              && drw["RECORDED_B"].ToString() != "")
            {
                itm.BackColor = System.Drawing.Color.FromArgb(204, 153, 255);
            }
            else
            {
                if (drw["InvestorName"] != DBNull.Value && drw["InvestorName"].ToString() != "")
                {
                    itm.BackColor = System.Drawing.Color.Yellow;
                }
                else
                {
                    itm.BackColor = System.Drawing.Color.White;
                }
            }
        }
    }

    void LvreoMasterList_Inserted(object sender, SqlDataSourceStatusEventArgs e)
    {
        var apn = e.Command.Parameters["@Apn"].Value.ToString();
      ImportDataAccess.UpdateLvReoAssmts(apn);

      DataAccess da = new DataAccess();
      DataTable dt = da.ExecuteSQL(string.Format("{0} @apn='{1}'", "getLvreo_PropertyInfo", apn));
      if (dt.Rows.Count == 0) return;

      string location = dt.Rows[0]["Location"].ToString();
      if (location.EndsWith(", "))
          location = location.Remove(location.Length - 2, 2);

      string rootDir = Server.MapPath("~/PropertiesFiles");
      MasterList.EnsurePropertyDirs(Session["User"] as User, rootDir, location, apn, false);
    }

    void SearchButton_Click(object sender, ImageClickEventArgs e)
    {
      Grid.Rebind();
      listFilter.ClearFilter();
    }

    protected override string GetPropertyDetailsColumnEditorID()
    {
      return edTextBox.ID;
    }

    protected override Control GetGridContainer()
    {
      return phGrid;
    }

    protected override string GetDataSourceID()
    {
      return sqlDataSource.ID;
    }

    protected void lnkExportToExcel_Click(object sender, EventArgs e)
    {
        //HideColumn("DeleteButton");
        //HideColumn("EditButton");
        //HideColumn("Address");

        //Grid.MasterTableView.ExportToExcel();

        Excel ex = Utilities.GetExcel();
        Worksheet ws = ex.Worksheets[0];

        DataAccess da = new DataAccess();
        DataTable dt = da.ExecuteSQL(string.Format("getLvreo_MasterList '{0}', '{1}', '{2}'",
          listFilter.Apn,
          listFilter.Address,
          listFilter.Zip));
        int startRow = 0;
        Utilities.GridToExcel(dt, Grid, ws, true, ref startRow);

        /*for (int i = 1; i < startRow; ++i)
        {
            ws.Cells[i, 4].Style.Custom = "mm/dd/yyyy";
            ws.Cells[i, 7].Style.Custom = "mm/dd/yyyy";
        }*/

        ex.Save("LvreoDownload.xls", FileFormatType.Excel2003, SaveType.OpenInExcel, HttpContext.Current.Response);
        HttpContext.Current.Response.End();
    }

    protected void lnkRefreshGrid_Click(object sender, EventArgs e)
    {
      Grid.Rebind();
    }

      protected void sqlDataSource_Selecting(object sender, SqlDataSourceSelectingEventArgs e)
    {
      //DataAccess da = new DataAccess();
      //CountsControl.SetCounts(
      //  da.ExecuteSQLRowCount("getLvreo_MasterList_ListingStatusCount 'Postponed'"),
      //  da.ExecuteSQLRowCount("getLvreo_MasterList_ListingStatusCount 'Cancelled'"),
      //  da.ExecuteSQLRowCount("getLvreo_MasterList_ListingStatusCount 'Sold To Bank'"),
      //  da.ExecuteSQLRowCount("getLvreo_MasterList_ListingStatusCount 'Sold To 3rd Party'"));
    }

    protected override SqlDataSource GetSqlDataSource()
    {
      return sqlDataSource;
    }

    protected override ListFilterControl GetListFilterControl()
    {
      return listFilter;
    }

    protected override bool IsEditable()
    {
      return CurrentUser.UserRole == UserRole.SuperAdmin
        || (CurrentUser.UserRole == UserRole.User
            && CurrentUser.LvreoRole == RoleAccess.ReadWrite)
        || (CurrentUser.UserRole == UserRole.InvestorAdmin
            && CurrentUser.SubRole == UserSubRole.LVReo);
    }

    protected override SourcePage GetSourcePage()
    {
        return SourcePage.LvreoMasterEdit;
    }

    protected override void SetupSqlDataSource(SqlDataSource dataSource)
    {
      base.SetupSqlDataSource(dataSource);

      dataSource.Selecting += new SqlDataSourceSelectingEventHandler(dataSource_Selecting);
    }

    void dataSource_Selecting(object sender, SqlDataSourceSelectingEventArgs e)
    {
      e.Command.Parameters["@showAllUnassigned"].Value = showAllUnassigned;
    }

    bool showAllUnassigned = false;

    protected void lnkShowUnassigned_Click(object sender, EventArgs e)
    {
      showAllUnassigned = true;
      Grid.Rebind();
    }    
  }
}